#include<iostream>
#include<assert.h>
#include<unistd.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

int main()
{
    //1.创建管道
    int pipefd[2]={0};
    int n = pipe(pipefd);
    assert(n!=-1);
    (void)n;//防止n在release下断言删除了

//#ifdef DEBUG
    cout<<"pipefd[0]"<<pipefd[0]<<endl;//读
    cout<<"pipefd[1]"<<pipefd[1]<<endl;//写
//endif

    //2.创建子进程（子进程负责读取，父进程写入）
    pid_t id = fork();
    assert(id!=-1);
    if(id==0)
    {
        //2.1关闭子进程读取；设置读取缓冲区；因为使用系统读取接口，所以需要手动末尾加0
        close(pipefd[1]);
        char buffer[1024];
        while(true)
        {
            ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(s>0)
            {
                buffer[s]=0;//读取成功后加|0
                cout<<"father:"<<buffer<<endl;
            }
        }
        exit(0);//关闭文件描述符
    }

    //3.父进程负责数据的写入:关闭读；设置写入缓冲区，利用snprintf，将写入的数据放入缓冲区中
    close(pipefd[0]);
    string message ="我是父进程，请求向你通信。";
    int count =0;
    char send_buffer[1024];
    while(true)
    {
        //将字符串信息发送到缓冲区中(构建一个变化的字符串)
        snprintf(send_buffer,sizeof(send_buffer),"%s[%d] :%d",message.c_str(),getpid(),count++);
        //写入信息
        write(pipefd[1],send_buffer,strlen(send_buffer));
        sleep(1);
    }

    pid_t ret = waitpid(id,nullptr,0);
    assert(ret<0);
    (void)ret;

    //父进程写入完毕后，关闭自己的写入功能
    close(pipefd[1]);

    return 0;
}